package cn.acewill.yxd.yunxundian.ui.sign;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.SelectLostRRAdapter;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.rJson;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.RMainUtils;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;

public class MulitpleLostRRActivity extends BaseActivity implements View.OnClickListener{
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private int schid;
    private RecyclerView myRecycle;
    private ArrayList<RMain> rMains;
    private  SelectLostRRAdapter adapter;
    private LinearLayout nodata;
    private Button timeBtn;
    //默认时间
    private int startYear,startMonth,startDay,hour,minute;
    private  ArrayList<Employee> emp;
    private String thisTime;
    private CheckBox selectAll;
    private TextView selectCount;
    private LinearLayout selectLinear;

    //  private boolean isAllCheck = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mulitple_lost_rr);
        initView();
        defultTime();
        if (NetWorkStateReceiver.whetherConnectNetWork==1){
            getTuiSongRenData();
        }else{
            try {
                loadRmain();
                getLostRRList();
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_preview_report,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.preview: //保存数据
          //      startActivity(new Intent(this,PreViewAcitivity.class).putExtra("schId",schid));
                saveData();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void initView(){
        schid = getIntent().getIntExtra("schid",-1);
        if (schid==-1){
            Toast.makeText(this,"数据获取失败",Toast.LENGTH_SHORT).show();
            finish();
        }
        Toolbar toolbar = (Toolbar) findViewById(R.id.myToolBar);
        toolbar.setTitle("");
        toolbar.setNavigationIcon(R.mipmap.back);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (adapter!=null){
                    showTipDialog();
                }else{
                    finish();
                }
            }
        });
        nodata = (LinearLayout) findViewById(R.id.nodata);
        timeBtn = (Button) findViewById(R.id.select_date);
        timeBtn.setOnClickListener(this);
        selectCount = findViewById(R.id.selectCount);
        selectAll = findViewById(R.id.selectAll);
        selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    if (adapter!=null){
                        adapter.setAllCheck();
                        selectCount.setText(adapter.getCheckString());
                    }
                }else{
                    if (adapter!=null){
                        adapter.disCheckAll();
                        selectCount.setText(adapter.getCheckString());
                    }
                }
            }
        });
        selectLinear = findViewById(R.id.selectLinear);

        try {
            tempLostRR rr = db.selector(tempLostRR.class).where("schId", "=", schid).findFirst();
            if (rr!=null){
                if (rr.getXiongdongTime()!=null&&!TextUtils.isEmpty(rr.getXiongdongTime())){
                    timeBtn.setText(rr.getXiongdongTime());
                    thisTime = rr.getXiongdongTime();
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        initRecycle();
    }

    public void initRecycle(){
        myRecycle = (RecyclerView) findViewById(R.id.myRecycle);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        myRecycle.setLayoutManager(manager);
        // myRecycle.addItemDecoration(new RecyclerViewDivider(this,LinearLayoutManager.VERTICAL,10,getResources().getColor(R.color.blue)));
        myRecycle.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
    }

    //根据日程id，查找当前失分项
    public void getLostRRList() throws DbException {

        List<tempLostRR> rrList = db.selector(tempLostRR.class).where("schId", "=", schid).
                and("empId","=", MainActivity.id).findAll();
        if (rrList !=null&& rrList.size()>0){
            nodata.setVisibility(View.GONE);
            //排除其他的可能
            List<tempLostRR> list = excludeSameRR(rrList);
            if (list!=null&&list.size()>0){
                adapter = new SelectLostRRAdapter(this, rrList, emp,rMains, new SelectLostRRAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(tempLostRR rr) {
                        //刷新数量
                        selectCount.setText(adapter.getCheckString());
                    }
                });
                myRecycle.setAdapter(adapter);
                selectCount.setText(adapter.getCheckString());
                selectLinear.setVisibility(View.VISIBLE);
            }else{
                nodata.setVisibility(View.VISIBLE);
                selectLinear.setVisibility(View.GONE);
            }
        }else{
            nodata.setVisibility(View.VISIBLE);
            selectLinear.setVisibility(View.GONE);
        }

    }
    //排除重复评估项
    public List<tempLostRR> excludeSameRR( List<tempLostRR> rrList){
        for  ( int i = 0; i<rrList.size()-1 ;i ++)  {
            for  ( int j = rrList.size() - 1 ;j > i;j --)  {
                if  (rrList.get(j).equals(rrList.get(i)))  {
                    rrList.remove(j);
                }
            }
        }
        return excludeFullMarkAndMinus(rrList);

    }
    //排除满分与分数为-1的情况
    public List<tempLostRR> excludeFullMarkAndMinus( List<tempLostRR> rrList){

        for (int i =0;i<rrList.size();i++){
            if (rrList.get(i).getScore()==-1||rrList.get(i).getScore()==getMaxScore(rrList.get(i).getRRowId())){
                rrList.remove(i);
                i=i-1;
            }
        }
        return rrList;
    }

    //获得评估表数据
    public void loadRmain() throws DbException {
        Schedule schedule=db.selector(Schedule.class).where("ID","=",schid).findFirst();
        sType type=db.selector(sType.class).where("ID","=",schedule.getSTypeID()).findFirst();
        rJson rmian = db.selector(rJson.class).where("ID", "=", type.getReportId()).findFirst();
        String json= rmian.getjSon();
        Gson gson=new Gson();
        Type typeList = new TypeToken<ArrayList<RMain>>() {
        }.getType();
        rMains = gson.fromJson(pubClass.convertToArrayJsonNormal(json), typeList);
    }

    //对应的Q2Bean
    public double getMaxScore(int rowid){
        if (rMains!=null){
            List<RMain.TablesBean> TableList=rMains.get(0).getTables();
            for (int i=0;i<TableList.size();i++) {
                List<RMain.TablesBean.RowsBean> rowlist = TableList.get(i).getRows();
                for (int k=0;k<rowlist.size();k++){
                    if (rowid == rowlist.get(k).getQ2().getID()){
                        if(rMains.get(0).getQ().getCountFunc()==3)
                        {
                            return 99999;
                        }
                        else
                            return rowlist.get(k).getQ2().getMaxScore();
                    }
                }
            }
        }
        //如果查不到返回what
        return 0;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.select_date:
//                SelectData data=new SelectData(this,true);
//                data.showAtLocation(timeBtn, Gravity.BOTTOM,0,0);
//                data.setDateClickListener(new SelectData.OnDateClickListener() {
//                    @Override
//                    public void onClick(String year, String month, String day, String hour, String minute) {
//                        String str=year+"-"+month+"-"+day+" "+hour+":"+minute;
//                        timeBtn.setText(str);
//                    }
//                });
//                DatePicker datePicker = new DatePicker(this);
                DatePickerDialog SdatePickerDialog=new DatePickerDialog(this,dataListener,startYear,startMonth-1,startDay);
                SdatePickerDialog.show();
                break;
        }
    }
    DatePickerDialog.OnDateSetListener dataListener = new DatePickerDialog.OnDateSetListener(){

        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            month = month+1;
            thisTime = year+"-"+month+"-"+dayOfMonth+" ";
            TimePickerDialog timePickerDialog = new TimePickerDialog(MulitpleLostRRActivity.this,timeSetListener,hour,minute,true);
            timePickerDialog.show();

        }
    };
    TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            if (hourOfDay<10){
                thisTime+="0"+hourOfDay+":" ;
            }else{
                thisTime+=hourOfDay+":" ;
            }
            if (minute<10){
                thisTime+="0"+minute;
            }else{
                thisTime+=minute;
            }
            try {
                timeAviable();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    };
    public void defultTime(){
        Calendar calendar=Calendar.getInstance();
        startYear=calendar.get(Calendar.YEAR);
        startMonth=calendar.get(Calendar.MONTH)+1;
        startDay=calendar.get(Calendar.DAY_OF_MONTH);
        hour = calendar.get(Calendar.HOUR);
        minute = calendar.get(Calendar.MINUTE);
    }

    public void saveData(){
        //无数据的时候adapter没有被实例化
        if (adapter!=null){
            if (adapter.getCheckItemList()!=null){ //有选择的数据
                if (TextUtils.isEmpty(thisTime)){
                    showToast(this,"请选择任务时间");
                }else{
                    List<tempLostRR> list = adapter.getCurrentList();
                    for (tempLostRR rr:list){
                        try {
                            rr.setXiongdongTime(thisTime);
                            db.saveOrUpdate(rr);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                    finish();
                }
            }else{
                //全部没选
                finish();
            }

        }
    }

    public void timeAviable() throws ParseException {
        if (thisTime.contains("-")){
            String nowTime = startYear+"-"+startMonth+"-"+startDay+" "+hour+":"+minute;
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm",Locale.getDefault());
            Date d1 = df.parse(nowTime);
            Date d2 = df.parse(thisTime);
            if (d1.getTime()>d2.getTime()){
                thisTime = "";
                Toast.makeText(this,"选择时间小于当前时间",Toast.LENGTH_SHORT).show();
            }else{
                if (adapter!=null){
                    List<tempLostRR> rrList = adapter.getCurrentList();
                    for (tempLostRR rr:rrList){
                        rr.setXiongdongTime(thisTime);
//                        try {
//                            db.saveOrUpdate(rr);
//                        } catch (DbException e) {
//                            e.printStackTrace();
//                        }
                    }
                }
                timeBtn.setText(thisTime);

            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            if (adapter!=null){
                showTipDialog();
                return false;
            }else{
                return super.onKeyDown(keyCode, event);
            }
        }else{
            return super.onKeyDown(keyCode, event);
        }

    }

    //获取行动计划人员
    public void getTuiSongRenData(){
        final ProgressDialog pdialog=new ProgressDialog(this);
        pdialog.setMessage("加载中");
        pdialog.show();
        Map<String,String> map=new HashMap<>();
        map.put("task","getShopTodoEmpList");
        map.put("schid",schid+"");
        Log.e("schid",schid+"");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String[] array=result.split("\\|");
                    if(array[0].equals("200")){
                        //
                        Gson gson=new Gson();
                        Type typeList=new TypeToken<ArrayList<Employee>>(){}.getType();
                        emp=gson.fromJson(pubClass.convertToArrayJson(result),typeList);
                        try {
                            loadRmain();
                            getLostRRList();
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                    if (pdialog.isShowing()){
                        pdialog.dismiss();
                    }
                }
                @Override
                public void onFailture() {
                    if (pdialog.isShowing()){
                        pdialog.dismiss();
                    }
                }
            },map);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void showTipDialog(){
        MaterialDialogUtils.showMoreBtnDialog(this, "是否保存数据", "确定", "取消", "否", true, false,
                new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        saveData();
                    }
                }, new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                }, new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        finish();
                    }
                });
    }


}
